﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
using System.Diagnostics;
using System.IO;
using Microsoft.TeamFoundation.Build.Client;
using System.Threading;

namespace TeamDeploy.Activities
{
    [BuildActivity(HostEnvironmentOption.Agent)]
    public sealed class CleanupPsExec : CustomActivityBase
    {
        [RequiredArgument]
        public InArgument<string> TargetMachine { get; set; }

        [RequiredArgument]
        public InArgument<string> KillAppPathFilename { get; set; }

        protected override void Execute(CodeActivityContext context)
        {

            try
            {
                string targetMachine = context.GetValue(this.TargetMachine);
                string killAppPathFilename = context.GetValue(this.KillAppPathFilename);

                string args;
                // Process proc;

                //
                // The goal is to run this command:  sc \\[TargetMachine] stop psexesvc
                //
                //Log.LogMessage("Stopping service psexesvc on " + TargetMachine + "...");
                args = @"\\" + targetMachine + " stop psexesvc";
                // proc = Process.Start("sc", args);

                using (System.Diagnostics.Process process = new System.Diagnostics.Process())
                {
                    process.StartInfo.FileName = "sc";
                    //process.StartInfo.WorkingDirectory = SearchPathRoot.Get(context);                    
                    process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
                    process.StartInfo.UseShellExecute = false;
                    process.StartInfo.ErrorDialog = false;
                    process.StartInfo.CreateNoWindow = true;
                    process.StartInfo.RedirectStandardOutput = true;
                    process.StartInfo.Arguments = args;

                    try
                    {
                        process.Start();
                        string output = process.StandardOutput.ReadToEnd();
                        process.WaitForExit();
                        LogMessage(context, "CleanupPSExec Output:" + output);
                    }
                    catch (Exception ex)
                    {
                        LogMessage(context, ex.ToString());
                        throw ex;
                    }
                    // proc.WaitForExit();

                    LogMessage(context, "Stopping service psexesvc on " + targetMachine + " returned code:" + process.ExitCode);
                }
                //if (proc.ExitCode == 0)
                //{
                //    Log.LogMessage(message);
                //}
                //else
                //{
                //    Log.LogWarning(message);
                //}

                var workflow = new KillProcess();
                workflow.TargetMachine = targetMachine;
                workflow.KillAppPathFilename = killAppPathFilename;
                workflow.ProcessName = "psexesvc";
                workflow.IgnoreExitCode = "true";
                // Create the workflow run-time environment

                AutoResetEvent waitHandle = new AutoResetEvent(false);
                WorkflowApplication workflowApplication = new WorkflowApplication(workflow);
                workflowApplication.Completed = delegate(
                    WorkflowApplicationCompletedEventArgs e)
                {

                    if (e.TerminationException != null)
                    {

                        LogMessage(context, e.TerminationException.Message);

                    }


                    waitHandle.Set();

                };

                workflowApplication.Run();
                waitHandle.WaitOne();

                args = @"\\" + targetMachine + " delete psexesvc";

                using (System.Diagnostics.Process process = new System.Diagnostics.Process())
                {
                    process.StartInfo.FileName = "sc";
                    //process.StartInfo.WorkingDirectory = SearchPathRoot.Get(context);                    
                    process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
                    process.StartInfo.UseShellExecute = false;
                    process.StartInfo.ErrorDialog = false;
                    process.StartInfo.CreateNoWindow = true;
                    process.StartInfo.RedirectStandardOutput = true;
                    process.StartInfo.Arguments = args;

                    try
                    {
                        process.Start();
                        string output = process.StandardOutput.ReadToEnd();
                        process.WaitForExit();
                        LogMessage(context, "Cleanup PSExec Output:" + output);
                    }
                    catch (Exception ex)
                    {
                        LogMessage(context, ex.ToString());
                        throw ex;
                    }

                }

                // delete the psexesvc file if it exists.
                string delPath = @"\\" + targetMachine + @"\admin$\psexesvc.exe";
                if (File.Exists(delPath))
                    File.Delete(delPath);

            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}
